package net.moao.netutils_library;

import android.annotation.SuppressLint;
import android.util.Log;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class NetUtils {
    public static final String TAG = "NetUtils";

    public static String Domain2IP(String domainName){
        try {
            Log.d(TAG, "将要转换的域名：" + domainName);
            InetAddress[] addresses = InetAddress.getAllByName(domainName);
            for (InetAddress address: addresses){
                Log.d(TAG, "转换为 ip 后：" + address.getHostAddress());
                return address.getHostAddress();
            }
        }catch (Exception e){
            Log.e(TAG, "域名解析失败：" + e.toString());
        }
        return "0.0.0.0";
    }

    /**
     * 域名解析成 ip 地址
     * @param domain 域名
     * @return ip 地址
     */
    public static String domain2ip(String domain){
        try {
            // 解析域名
            InetAddress address = InetAddress.getByName(domain);
            // 获取IP地址
            String ipAddress = address.getHostAddress();
            Log.d(TAG, "域名 : " + domain);
            Log.d(TAG, "IP 地址 : " + ipAddress);
            return ipAddress;
        } catch (UnknownHostException e) {
            Log.e(TAG, "域名解析失败：" + e.getMessage());
            return "0.0.0.0";
        }
    }

    /**
     * 获取本机 ip 地址(安卓手机开热点时候用)
     * @return 返回 ip 地址
     */
    public static String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            Log.i("TcpServer", "SocketException");
            e.printStackTrace();
        }
        return hostIp;
    }
}
